//
//  ZSComposeViewController.swift
//  ZSWeibo
//
//  Created by zsj1992 on 16/4/15.
//  Copyright © 2016年 ichange. All rights reserved.
//

import UIKit

/// 这是点击了发布界面上的按钮进入的控制器,在这个控制器上面进行发布微博的操作


class ZSComposeViewController: UIViewController {
    
    
    /// 懒加载一个keyBoardView
    lazy var keyBoardView : HMEmoticonKeyboardView = HMEmoticonKeyboardView()
    
    
    
    
    /**viewDidLoad方法*/
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        setupUI()
        registerNitification()
        
        self.view.backgroundColor = UIColor.whiteColor()
    }
    
    //MARK: -触摸屏幕的方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        view.endEditing(true)
    }
    
    // MARK: - 懒加载控件
    private lazy var textView : HMEmoticonTextView = {
        let v = HMEmoticonTextView()
        
        v.font = UIFont.systemFontOfSize(18)
        
        
        v.backgroundColor = UIColor(red: 222/255.0, green: 222/255.0, blue: 222/255.0, alpha: 1.0)
        
        v.alwaysBounceVertical = true
        
        v.keyboardDismissMode = .OnDrag
        
        v.delegate = self//设置代理监听textView的changeValue等方法
        
        return v
    }()
    
    
    
    lazy var lbl : UILabel = {
        
        let lbl = UILabel()
        
        lbl.text = "听说下雨天音乐和辣条更配哦"
        
        lbl.textColor = UIColor.lightGrayColor()
        
        lbl.font = UIFont.systemFontOfSize(18)
        
        lbl.sizeToFit()
        
        return lbl
    }()
    
    /// 自定义底部toolBar
    lazy var toolBar : UIToolbar = {
        
        let toolBar = UIToolbar()
        
        //字典数组保存底部按钮的图片及对应的方法名
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        var items = [UIBarButtonItem]()
        
        for dic in itemSettings{
            
            let btn = UIBarButtonItem.creatItem(dic["imageName"], target: self, action:  Selector(dic["actionName"]!))
            
            let flex = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(btn)
            
            items.append(flex)
        }
        
        //移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
        return toolBar
    }()
    
    
    
    
    //添加一个选择图片的控制器
    lazy var pictureSelector:ZSPictureSelectorController = ZSPictureSelectorController()
    
    
    // MARK: - 把控件添加到控制器的view上面
    func setupUI(){
        
        self.addChildViewController(pictureSelector)
        
        textView.addSubview(lbl)
        
        view.addSubview(textView)
        
        view.addSubview(pictureSelector.collectionView!)
        
        view.addSubview(toolBar)
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.left.right.top.equalTo(self.view)
            
            make.top.equalTo(view).offset(64)
            
            make.height.equalTo(screenHeight/3)
        }
        
        
        lbl.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(textView).offset(4.5)
            make.top.equalTo(textView).offset(8)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(self.view)
        }
        
        
        pictureSelector.collectionView!.snp_makeConstraints { (make) -> Void in
            pictureSelector.collectionView?.backgroundColor  = UIColor.whiteColor()
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        }
    }
}





// MARK: - UI相关扩展
extension ZSComposeViewController{
    /**设置导航控制器*/
    func setupNav(){
        //导航栏左边的item
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatItem( target: self, action: "close", title: "关闭")
        
        //导航栏右边的item
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFontOfSize(16)
        btn.setTitle("发送", forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        btn.cornerRadius = 5
        
        
        btn.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
        
        
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
}




// MARK: - 逻辑相关扩展
extension ZSComposeViewController{
    
    /**关闭控制器的方法*/
    func close(){
        
        self.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    /**实现toolBar的点击事件*/
     /**
     目前只实现了一个选择图片并进行发送的方法,字典中只配置了这一个(两个)方法,以后对应的每个按钮对应的方法都必须进行实现
     */
    func selectPicture(){
        print("点击了toolBar的按钮-->选择图片")
        
        pictureSelector.collectionView?.snp_updateConstraints(closure: { (make) -> Void in
            
            make.height.equalTo(screenHeight*2/3)
        })
    }
    
    //选择表情
    func selectEmoticon(){
        print("点击了toolBar的按钮-->选择表情")
        
        //textView 如果为 nil 就会显示系统键盘
//        print(textView.inputView)
        textView.inputView = (keyBoardView.inputView == nil ? keyBoardView : nil)
      
        //切换了inputView之后需要进行reloadInputView
        textView.reloadInputViews()
        //如果不是第一响应者 就成为第一响应者
        if !textView.isFirstResponder() {
            
            textView.becomeFirstResponder()
        }
    }
    
    
    
    //这是通知调用的插入文字的方法
    @objc private func insertEmoticonText(n: NSNotification) {
//        print(n)
        //处理用户点击事件
        guard let em = n.object as? HMEmoticon else {
            print("噢 出大事啦")
            return
        }
        
        //这是真的把文字等插入到textView中...
        textView.insertEmotioncText(em)
    }

    
    //发送图片
    func send(){
        
        print("发送图片")
        
        
//发送状态不是就是直接在UI上面进行显示,而是发送到服务器上面,(就叫做发送微博)之后要进行显示,还需要再从服务器进行请求
//所以其实呢,你在textView上面显示了表情图片,其实和微博上面显示的内容没有什么关系,,,你要想在UI上面显示图片表情-->需要对ViewModel进行处理  -->然后在UI上面的label上面显示属性文本

        
        
ZSNetworkTools.sharedTools.sendStatus((ZSUserAccountViewModel.sharedUserViewModel.userAccount?.access_token)!, status: textView.showFullText(), imageList: pictureSelector.imageList) { (result, error) -> () in
            
            if error != nil{
                print(error)
            }else{
                
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    
                })
            }
        }
    }
}



// MARK: - 实现代理方法的类扩展
extension ZSComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView){
        //隐藏占位lbl
        
        lbl.hidden = self.textView.hasText()
        
        
        navigationItem.rightBarButtonItem?.enabled = self.textView.hasText()
    }
}

// MARK: - 通知机制监听键盘的弹出事件等
extension ZSComposeViewController{
    
    //在一个方法中进行通知的注册
    func registerNitification(){
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "UIKeyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertEmoticonText:", name: HMEmoticonBtnDidClick, object: nil)
    }
    
    
    //这个方法实现对通知的监听
    func UIKeyboardWillChangeFrame(n:NSNotification){
        
//        print(n)
        
        let userInfo = n.userInfo!
        
        let rect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        /**更新约束*/
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(rect.origin.y-screenHeight)
        }
        
        /**刷新页面*/
        UIView.animateWithDuration(0.25){ () -> Void in
            self.view.layoutIfNeeded()
        }
    }
}







